package com.xyc.petmallsystem.controller;

import com.xyc.petmallsystem.pojo.Cat;
import com.xyc.petmallsystem.repository.CatRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Joel
 * @date 2021/11/28
 */

@RestController
@RequestMapping("/cat")
public class CatController {
    @Autowired
    CatRepository catRepository;

    /*
    查询所有
     */
    @GetMapping("/find")
    public List<Cat> find() {
        return catRepository.findAll();
    }

    /*
   分页  全部
    */
    @GetMapping("/findPage/{page}/{size}")
    public Page<Cat> findPage(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest pageable = PageRequest.of(page - 1, size);
        return catRepository.findAll(pageable);
    }

    /*
   找出所有 某种猫类
    */
    @GetMapping("/findCat/{sort}")
    public List<Cat> findCat1(@PathVariable String sort) {
        List<Cat> catList = catRepository.findCat(sort);
        System.out.println("分类-" + sort + " " + catList);
        return catList;
    }


    /*
    根据id查找
     */
    @GetMapping("/findById/{id}")
    public Cat findById(@PathVariable("id") Integer id) {
        return catRepository.findById(id).get();
    }

    /*
    修改信息
     */
    @PutMapping("/update")
    public String update(@RequestBody Cat cat) {
        Cat result = catRepository.save(cat);
        if (result != null)
            return "success";
        return "error";
    }

    /*
    根据id来删除
     */
    @DeleteMapping("/del/{id}")
    public void del(@PathVariable("id") Integer id) {
        catRepository.deleteById(id);
    }


    /*
    新增
     */
    @PostMapping("/save")
    public String save(@RequestBody Cat cat) {
        Cat result = catRepository.save(cat);
        if (result != null)
            return "success";
        return "error";
    }

    /*
    JPA 模糊查询
     */
    @GetMapping("/search/{content}")
    public List<Cat> search(@PathVariable String content) {
        List<Cat> catList = catRepository.search("%" + content.trim() + "%");
        System.out.println("搜索内容为:" + content);
        if (catList != null) {
            System.out.println("搜索结果:");
            for (Cat cat : catList) {
                System.out.println(cat);
            }
        } else {
            System.out.println("搜索结果为空");
        }
        return catList;
    }
}
